package it.polimi.swimv2.session;

import it.polimi.swimv2.entities.AbstractUser;
import it.polimi.swimv2.entities.User;
import it.polimi.swimv2.exception.UserDataError;
import it.polimi.swimv2.exception.UserDataException;
import it.polimi.swimv2.remote.RegistrationManagerRemote;
import it.polimi.swimv2.util.UserDataValidator;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class RegistrationManager
 */
@Stateless
public class RegistrationManager implements RegistrationManagerRemote {

	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;

	/**
	 * Default constructor.
	 */
	public RegistrationManager() {
		super();
	}

	@Override
	public User createNewUser(String username, String password,
			String firstname, String surname, String email, String phone,
			String city) throws UserDataException {
		
		User newUser = new User(username,password,firstname,surname,email);
		newUser.setPhone(phone);
		newUser.setCity(city);

		checkDataValidity(newUser);

		storeNewUser(newUser);

		return newUser;
	}

	private void checkDataValidity(User newUser) throws UserDataException {
		if (em.find(AbstractUser.class, newUser.getUsername()) != null) {
			throw new UserDataException(UserDataError.USERNAMEERR);
		}
		if(!UserDataValidator.usernameIsValid(newUser.getUsername())){
			throw new UserDataException(UserDataError.USERNAMEERR); 
		}
		if(!UserDataValidator.passwordIsValid(newUser.getPassword())){
			throw new UserDataException(UserDataError.PWDERR);
		}
		if(!UserDataValidator.emailIsValid(newUser.getEmail())){
			throw new UserDataException(UserDataError.EMAILERR);
		}
		if(!UserDataValidator.phoneIsValid(newUser.getPhone())){
			throw new UserDataException(UserDataError.PHONEERR);
		}
		if(!UserDataValidator.cityIsValid(newUser.getCity())){
			throw new UserDataException(UserDataError.CITYERR);
		}
		if(!UserDataValidator.nameIsValid(newUser.getFirstname(), newUser.getSurname())){
			throw new UserDataException(UserDataError.NAMEERR);
		}
	}

	private void storeNewUser(User newUser) {
		em.persist(newUser);
		em.flush();
	}

}
